<?php
namespace app\admin\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Db;
use think\facade\Cookie;
class Index extends BaseController
{
    public $redis = null;
    public function initialize()
    {
        $this->redis = new \Redis();
        // 连接到Redis服务器
        $this->redis->connect('127.0.0.1', 6379);
    }
    public function index()
    {
        if(!$data = Cookie::get('user_data'))
        {
            return redirect(url('index/login'));
        }

        $data = json_decode($data,true);

        $list = $this->redis->lrange('user_list', 0, -1);
        
        View::assign('user_data',$data);
        View::assign('list',$list);
        return View::fetch();
    }
    // 检查某个值是否存在于列表中
    function valueExistsInList($redis, $listName, $value) {
        $length = $redis->lLen($listName); // 获取列表长度
        for ($i = 0; $i < $length; $i++) {
            if ($redis->lIndex($listName, $i) === $value) {
                return true; // 找到值
            }
        }
        return false; // 未找到值
    }
    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }

    public function login()
    {
       
       
       
        if($this->request->isPost())
        {
            $uid = 0;
            $params = $this->request->post();

            $find = Db::table('fa_admin')->where('name', $params['name'])->find();
            if(!$find)
            {
                $time = time();
                $data = ['name' => $params['name'], 'createtime' => $time,'updatetime'=>$time];
                $res = Db::name('admin')->insert($data);
                if(!$res)
                {
                    return View::fetch();
                }
                $uid = Db::name('admin')->getLastInsID();
            }
            else
            {
                $uid = $find['id'];
            }

            $data = [
                'name' => $params['name'],
                'uid' => $uid,
                'fd' => 0,
            ];
            if (!$this->valueExistsInList($this->redis, 'user_list', $params['name'])) {
                $this->redis->lpush('user_list', $params['name']);//redis 保存用户列表
            }


            // 将数组序列化为 JSON 字符串
            $jsonData = json_encode($data);
            // 设置 Cookie，有效期为 1 天
            Cookie::set('user_data', $jsonData, 86400);

           /* View::assign('name',$params['name']);
            View::assign('user_data',$data);
            return View::fetch('index');*/

            return redirect(url('index/index'));

        }

        if($data = Cookie::get('user_data'))
        {
            return redirect(url('index/index'));
        }
        return View::fetch();
    }
}
